package com.ljh.account.controller;

import com.google.code.kaptcha.Producer;
import com.ljh.account.utils.Response;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;


@RestController
@RequestMapping("/api")
public class CaptchaController {
    @Autowired
    private Producer kaptchaProducer;

//    生成验证码
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 这里可以添加你的验证码生成逻辑
        String captchaText = kaptchaProducer.createText();
        // 生成验证码图片
        BufferedImage captchaImage = kaptchaProducer.createImage(captchaText);

        // 设置响应类型
        response.setContentType("image/jpeg");
        // 将验证码文本保存到session中以供后续验证
        request.getSession().setAttribute("captcha", captchaText);
        // 将图片写入响应
        ImageIO.write(captchaImage, "jpg", response.getOutputStream());
    }


//    校验验证码
    @GetMapping("/verify")
    public Response verifyCaptcha(@RequestParam("captcha") String captcha, HttpServletRequest request) {
        String storedCaptcha = (String) request.getSession().getAttribute("captcha");
        String lowcaptcha = captcha.toLowerCase();
        if (storedCaptcha != null ) {
            storedCaptcha = storedCaptcha.toLowerCase();
            if (storedCaptcha.equals(lowcaptcha)){
                return Response.success("验证码验证成功");
            }
        }
        return Response.success("验证码验证失败");

    }
}